import React, {
  FC,
  ReactElement,
  useState,
  useEffect,
  useRef,
  useCallback,
  useMemo,
} from 'react'
import style from '../index.less'
import { Select, Button, Spin } from 'antd'
import commonStyle from '@/pages/publicStyle'
import {
  CloseCircleFilled,
  CaretUpOutlined,
  CaretDownOutlined,
  LoadingOutlined,
  CheckCircleFilled,
} from '@ant-design/icons'
import CollapseCom from '@/components/CollapseCom'
import SignUp from './SignUp'
import Vote from './Vote'
import { connect } from 'umi'
import SignIn from './SignIn'
import { OverForm, TypeList } from '../../index.d'

const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />

// 快捷样式
const initStyle = {
  subtitleSize: {
    fontSize: '12px',
    color: '#b9b9b9',
  },
  checkedType: {
    background: '#1890ff',
    color: '#fff',
  },
  formBorderBox: {
    border: '1px solid rgb(0,0,0,0.06)',
  },
}
interface IProps {
  goForPrev: () => void
  defaultFormData: any
  releaseForm: () => void
  saveDrafts: () => void
  dispatch: () => void
}

const ActivityInfo: FC<IProps> = (props): ReactElement => {
  // 报名表单存储
  const [SignUpData, setSignUpData] = useState(null)
  // 投票表单存储
  const [VoteData, setVoteData] = useState(null)
  // 门票表单存储
  const [TicketData, setTicketData] = useState(null)
  // 签到表单存储
  const [SignInData, setSignInData] = useState(null)
  // 活动类型列表
  const [typeList, setTypeList] = useState<TypeList[]>(initTypeList)
  const SignUpForm: any = useRef(null)
  const VoteForm: any = useRef(null)
  const TicketForm: any = useRef(null)
  const SignInForm: any = useRef(null)
  // 改变活动类型列表的选中状态
  const checkActivityType = (
    e: React.MouseEvent,
    index: number,
    result: boolean,
  ) => {
    e.stopPropagation()

    setTypeList(
      typeList.map((item, TIndex) => {
        if (TIndex === index) {
          item.checked = result
          item.openState = result
        }
        return item
      }),
    )
  }
  const changeCollapseOpen = (index: number) => {
    setTypeList(
      typeList.map((item, TIndex) => {
        if (TIndex === index) item.openState = !item.openState
        return item
      }),
    )
  }
  // 暂存表单数据
  const saveFormData = useCallback((moduleData: any, saveName: string) => {
    switch (saveName) {
      case 'SignUpData':
        setSignUpData(moduleData)
        break
      case 'VoteData':
        setVoteData(moduleData)
        break
      case 'TicketData':
        setTicketData(moduleData)
        break
      case 'SignInData':
        setSignInData(moduleData)
        break
      default:
        break
    }
  }, [])
  let checkList: any = []
  let dataList: any = []
  let timer: any
  let OverFormCheck = (isSavenoCheck: boolean) => {
    let resultObj: OverForm = {
      isSignUp: false,
      isVote: false,
      isRobTickets: false,
      isSignIn: false,
      isLuckyDraw: false,
      activityVOS: dataList,
    }
    typeList.reduce((result: any, item: any) => {
      if (isSavenoCheck || item.isSubmit) {
        result[`is${item.type}`] = item.checked
      }
      return result
    }, resultObj)
    return resultObj
  }
  // 表单校验事件
  const checkForm = (formNode: any) => {
    return formNode.validateFields()
  }
  function goForCheck(index: number) {
    checkList[index]().then((nameList: any) => {
      const typeName = typeList.filter(item => item.checked)[index].name
      setTimeout(() => {
        setTypeList(
          typeList.map((item: any) => {
            if (item.name === typeName) {
              item.openState = false
              item.isSubmit = true
            }
            return item
          }),
        )
        if (index !== checkList.length - 1) goForCheck(index + 1)
        else {
          props.dispatch({
            type: 'maskModel/openMaskModel',
            payload: {
              maskModelShow: true,
              maskModelText: '发布中...',
            },
          })
          setTimeout(() => {
            props.dispatch({
              type: 'maskModel/openMaskModel',
              payload: {
                maskModelShow: false,
                maskModelText: '发布中...',
              },
            })
            props.releaseForm(OverFormCheck(false))
          }, 1500)
        }
      }, 1000)
    })
  }
  // 运行表单校验
  const checkGo = (checkFun: any) => {
    checkList.push(checkForm.bind(this, checkFun.form))
    dataList.push(checkFun.getOverFormData())
    clearTimeout(timer)
    timer = setTimeout(() => {
      goForCheck(0)
    })
  }
  // 提交表单
  const submitForm = () => {
    setTimeout(() => {
      setTypeList(
        typeList.map(item => {
          if (item.checked) {
            item.openState = true
          }
          return item
        }),
      )
      typeList.forEach(item => {
        if (item.openState) {
          switch (item.name) {
            case '报名':
              checkGo(SignUpForm.current)
              break
            case '投票':
              checkGo(VoteForm.current)
              break
            case '门票':
              checkGo(TicketForm.current)
              break
            case '签到':
              checkGo(SignInForm.current)
              break
            default:
              break
          }
        }
      })
    }, 0)
  }
  // 获取当前已有数据
  const getCurrentData = () => {
    let resultObj: OverForm = {
      isSignUp: false,
      isVote: false,
      isRobTickets: false,
      isSignIn: false,
      isLuckyDraw: false,
      activityVOS: [],
    }
    typeList.reduce((result: any, item: any) => {
      if (item.checked) {
        result[`is${item.type}`] = item.checked
        switch (item.type) {
          case 'SignUp':
            resultObj?.activityVOS!.push(
              item.openState
                ? SignUpForm.current.getOverFormData()
                : SignUpData,
            )
            break
          case 'Vote':
            resultObj?.activityVOS!.push(
              item.openState ? VoteForm.current.getOverFormData() : VoteData,
            )
            break
          case 'Ticket':
            resultObj?.activityVOS!.push(
              item.openState
                ? TicketForm.current.getOverFormData()
                : TicketData,
            )
            break
          case 'SignIn':
            resultObj?.activityVOS!.push(
              item.openState
                ? SignInForm.current.getOverFormData()
                : SignInData,
            )
            break
          default:
            break
        }
      }
      return result
    }, resultObj)
    return resultObj
  }
  // 上一步
  const goforPrev = () => {
    props.goForPrev(getCurrentData(), 0)
  }
  // 保存草稿
  const saveMust = () => {
    props.saveDrafts(getCurrentData(), 'second')
  }
  useEffect(() => {
    let getData = JSON.parse(JSON.stringify(props.defaultFormData))
    let oldTypeList = JSON.parse(JSON.stringify(typeList))
    getData.activityVOS.forEach((item: any) => {
      switch (item?.activityType) {
        case 1:
        case '1':
          oldTypeList[0].checked = true
          oldTypeList[2].checked = true
          setSignUpData(item)
          break
        case 2:
        case '2':
          oldTypeList[1].checked = true
          setVoteData(item)
          break
        case 3:
        case '3':
          oldTypeList[2].checked = true
          setTicketData(item)
          break
        case 4:
        case '4':
          oldTypeList[3].checked = true
          setSignInData(item)
          break
        default:
          break
      }
    })
    setTypeList(oldTypeList)
  }, [props.defaultFormData])
  const {
    detailCardBox,
    detailCommonTitle,
    activityTypeBox,
    actionBtnBox,
    activityTypeLabel,
  } = style
  const { checkedType, subtitleSize } = initStyle
  const { mt20, mr10, pl10, pt30, pb30 } = commonStyle
  return (
    <>
      <div className={detailCardBox} style={mt20}>
        <div className={detailCommonTitle}>
          选择你想要创建的活动<span style={subtitleSize}>（可添加多条）</span>
        </div>
        <div className={activityTypeBox} style={{ ...pl10, ...mt20 }}>
          {typeList.map((item, index) => (
            <div
              key={index}
              onClick={e => {
                checkActivityType(e, index, !item.checked)
              }}
              className={activityTypeLabel}
              style={{ ...(item.checked ? checkedType : ''), ...mr10 }}
            >
              {item.name}
            </div>
          ))}
        </div>
      </div>
      <div className={detailCardBox} style={mt20}>
        {typeList.map((item, index) =>
          item.checked ? (
            <CollapseCom
              key={index}
              headerBg="#e6f7ff"
              onClick={() => {
                changeCollapseOpen(index)
              }}
              headerTitle={item.name}
              openState={item.openState}
              headerExtra={
                <div>
                  {item.openState ? (
                    <div>
                      收起
                      <CaretUpOutlined />
                    </div>
                  ) : (
                    <div>
                      展开
                      <CaretDownOutlined />
                    </div>
                  )}
                </div>
              }
            >
              {item.name === '报名' ? (
                <SignUp
                  ref={SignUpForm}
                  typeId="SignUp"
                  isDrop={item.openState}
                  SignUpData={SignUpData}
                  saveFormData={saveFormData}
                ></SignUp>
              ) : item.name === '投票' ? (
                <Vote
                  ref={VoteForm}
                  isDrop={item.openState}
                  VoteData={VoteData}
                  saveFormData={saveFormData}
                ></Vote>
              ) : item.name === '门票' ? (
                <SignUp
                  ref={TicketForm}
                  typeId="Ticket"
                  isDrop={item.openState}
                  SignUpData={TicketData}
                  saveFormData={saveFormData}
                ></SignUp>
              ) : item.name === '签到' ? (
                <SignIn
                  ref={SignInForm}
                  isDrop={item.openState}
                  SignInData={SignInData}
                  saveFormData={saveFormData}
                ></SignIn>
              ) : (
                ''
              )}
            </CollapseCom>
          ) : (
            <div key={index}></div>
          ),
        )}

        <div className={actionBtnBox} style={{ ...pt30, ...pb30 }}>
          <Button
            type="primary"
            style={mr10}
            onClick={() => {
              submitForm()
            }}
          >
            发布
          </Button>
          <Button onClick={saveMust}>保存草稿</Button>
          <Button style={mr10}>预览</Button>
          <Button
            style={mr10}
            onClick={() => {
              goforPrev()
            }}
          >
            上一步
          </Button>
        </div>
      </div>
    </>
  )
}
export default connect(({ maskModel }: any) => ({ maskModel }))(ActivityInfo)

const initTypeList: TypeList[] = [
  {
    name: '报名',
    type: 'SignUp',
    value: '1',
    checked: false,
    openState: false,
    isSubmit: false,
  },
  {
    name: '投票',
    type: 'Vote',
    value: '2',
    checked: false,
    openState: false,
    isSubmit: false,
  },
  {
    name: '门票',
    type: 'Ticket',
    value: '3',
    checked: false,
    openState: false,
    isSubmit: false,
  },
  {
    name: '签到',
    type: 'SignIn',
    value: '4',
    checked: false,
    openState: false,
    isSubmit: false,
  },
]
//
